package com.kushe.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.UUID;

/**
 * Created by WhiteBlue on 15/6/8.
 */
public class ImagesUtil {
    private static String key = "4hJzZE2plxq8863g";
    private static String secret = "DUkC91RSEyoOPCfQenToIXHuDygbDm";
    private static String endpoint = "http://oss-cn-shenzhen.aliyuncs.com";
    public static String yun_url = "http://kushe1.oss-cn-shenzhen.aliyuncs.com/";


    public static File BytesToFile(String bytes, File dir) {
        try {
            if (dir.exists())
                dir.delete();
            dir.mkdir();
            String BasePath = dir.getPath();
            if (!BasePath.endsWith(File.separator)) {
                BasePath = BasePath + File.separator;
            }

            String uuid = UUID.randomUUID().toString();
            StringBuffer sbRealPath = new StringBuffer();
            sbRealPath.append(BasePath).append(uuid).append(".png");
            dir = new File(sbRealPath.toString());
            dir.createNewFile();

            byte[] base64 = new BASE64Decoder().decodeBuffer(bytes);
            FileOutputStream outputStream = new FileOutputStream(dir);

            outputStream.write(base64);
            outputStream.flush();
            outputStream.close();

            return dir;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static boolean putImage(File img) {
        try {
            OSSClient client = new OSSClient(endpoint, key, secret);
            InputStream up_stream = new FileInputStream(img);
            ObjectMetadata meta = new ObjectMetadata();
            meta.setContentLength(img.length());
            client.putObject("kushe0", img.getName(), up_stream, meta);

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
